﻿#include "playerwidget.h"
#include "ui_playerwidget.h"
#include <QFileDialog>
#include <QDebug>
#include <QTime>
#include <QIcon>
#include <QMouseEvent>

PlayerWidget::PlayerWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::PlayerWidget)
{
    ui->setupUi(this);

    //去掉窗口标题栏
    //setWindowFlag(Qt::FramelessWindowHint);
    //保持窗口在最上层
    //setWindowFlag(Qt::WindowStaysOnTopHint);

    videoWin = new VideoWin;
    //设置播放窗口图标
    videoWin->setWindowIcon(QIcon(":/icons/video-x-generic.svg"));
    player = new QMediaPlayer(this);
    ui->playButton->setDisabled(true);
    ui->stopButton->setDisabled(true);
    //通过信号获取音频文件的播放总时长
    connect(player, &QMediaPlayer::durationChanged,
            this, &PlayerWidget::updateDuration);
    //通过信号获取当前播放时长
    connect(player, &QMediaPlayer::positionChanged,
            this, &PlayerWidget::updatePosition);
    //通过信号获取滑动条当前位置
    connect(ui->progress, &QSlider::sliderMoved,
            player, &QMediaPlayer::setPosition);
    //处理音量修改
    connect(ui->volumeSlider, &QSlider::valueChanged,
            player, &QMediaPlayer::setVolume);
    //处理播放器状态变化
    connect(player, &QMediaPlayer::stateChanged,
            this, &PlayerWidget::updateState);
    //判断播放的文件中是否包含视频
    connect(player, &QMediaPlayer::videoAvailableChanged,
            videoWin, &QVideoWidget::setVisible);
    //设置视频输出窗口
    player->setVideoOutput(videoWin);
    //处理视频播放窗口的关闭信号
    connect(videoWin, &VideoWin::closeAll,
            this, &PlayerWidget::close);
    connect(this, &PlayerWidget::closeAll,
            videoWin, &VideoWin::close);

    //处理快进和回退
    connect(videoWin, &VideoWin::forward,
            this, &PlayerWidget::forward);
    connect(videoWin, &VideoWin::backward,
            this, &PlayerWidget::backward);

    //创建播放列表
    playlist = new QMediaPlaylist(this);

    //高亮显示当前正在播放的文件
    connect(playlist, &QMediaPlaylist::currentIndexChanged,
            this, &PlayerWidget::updateIndex);

    //双击播放选中的文件
    connect(ui->playlistWidget, &QListWidget::itemDoubleClicked,
            this, &PlayerWidget::playItem);
}

PlayerWidget::~PlayerWidget()
{
    delete ui;
}

void PlayerWidget::on_openButton_clicked()
{
    //显示打开文件对话框
    auto files = QFileDialog::getOpenFileUrls(this,
                                            tr("Select Open file"),
                                            QUrl("file:///C:/Users/geez/Music"),
                                            tr("Audio (*.ogg *.mp3 *.wav);;Video (*.mp4 *.mkv *.avi)"));
    //当打开文件不为空时启用播放按钮
    if (!files.isEmpty())
    {
        ui->playButton->setEnabled(true);
    }

    //将文件添加到播放列表
    for(auto& file: files)
    {
        playlist->addMedia(file);
        ui->playlistWidget->addItem(file.fileName());
    }

    player->setPlaylist(playlist);

    //player->setMedia(file);

    //setWindowTitle(windowTitle() + " - " + file.fileName());
    //player->play();
}

void PlayerWidget::on_playButton_clicked(bool checked)
{
    //按钮按下开始播放
    if (checked)
    {
        player->play();
    }
    else
    {
        player->pause();
    }
}

//获取音频播放总时长
void PlayerWidget::updateDuration(qint64 druation)
{
    ui->progress->setMaximum(druation);
    QTime total(0, 0);
    total = total.addMSecs(druation);
    ui->totalTime->setText(total.toString());
}

void PlayerWidget::updatePosition(qint64 position)
{
    //更新滑动条当前位置
    ui->progress->setSliderPosition(position);
    QTime time(0, 0);
    time = time.addMSecs(position);
    ui->playTime->setText(time.toString());
}

void PlayerWidget::on_toolButton_clicked(bool checked)
{
    if (checked)
    {
        player->setMuted(true);
    }
    else
    {
        player->setMuted(false);
    }
}


void PlayerWidget::on_speedBox_valueChanged(double arg1)
{
    player->setPlaybackRate(arg1);
}

void PlayerWidget::updateState(QMediaPlayer::State state)
{
    if (state == QMediaPlayer::StoppedState
        || state == QMediaPlayer::PausedState)
    {
        ui->playButton->setText(tr("Play"));
        ui->playButton->setIcon(QIcon(":/icons/media-playback-start-symbolic.svg"));
        ui->playButton->setChecked(false);
        ui->stopButton->setDisabled(true);
    }

    if (state == QMediaPlayer::PlayingState)
    {
        //将播放按钮上的文本修改为暂停
        ui->playButton->setText(tr("Pause"));
        ui->playButton->setIcon(QIcon(":/icons/media-playback-pause-symbolic.svg"));
        ui->playButton->setChecked(true);
        ui->stopButton->setDisabled(false);
    }
}

void PlayerWidget::on_stopButton_clicked()
{
    player->stop();
}

void PlayerWidget::closeEvent(QCloseEvent *event)
{
    Q_UNUSED(event);
    emit closeAll();
}

//快进
void PlayerWidget::forward()
{
    player->setPosition(player->position() + 10*1000);
}

//回退
void PlayerWidget::backward()
{
    player->setPosition(player->position() - 10*1000);
}

//切换上一个文件
void PlayerWidget::on_prevButton_clicked()
{
    playlist->previous();
}

//切换下一个文件
void PlayerWidget::on_nextButton_clicked()
{
    playlist->next();
}

//更新播放列表当前索引
void PlayerWidget::updateIndex(int index)
{
    //选中当前正在播放的文件
    ui->playlistWidget->setCurrentRow(index);
    //在播放窗口标题栏上显示文件名
    videoWin->setWindowTitle(playlist->currentMedia().canonicalUrl().fileName());
}

void PlayerWidget::playItem(QListWidgetItem *item)
{
    //根据列表项找到对应的行号
    int index = ui->playlistWidget->row(item);
    //切换到指定文件播放
    playlist->setCurrentIndex(index);
}

void PlayerWidget::on_clearButton_clicked()
{
    playlist->clear();
    ui->playlistWidget->clear();
}
